package cn.chenfeifx.checker.model;

import cn.chenfeifx.checker.eneity.ExportDataModel;
import cn.chenfeifx.checker.eneity.MessageEntity;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class ExportFile {


    public static void main(String[] args){
        try {
            List<ExportDataModel> data = new ArrayList<>();
            ExportDataModel exportDataModel = new ExportDataModel();
            exportDataModel.setArchiveId("001");
            //exportDataModel.setFileIntegrity("√");
            //exportDataModel.setFileAccuracy("√");
            exportDataModel.setPictureCount(56);
            exportDataModel.setPictureClarity("√");
            exportDataModel.setPictureMatching("√");
            exportDataModel.setPictureRepeatability("√");
            //exportDataModel.setMaterialCatalogCount(52);
            exportDataModel.setMaterialCatalogIntegrity("√");
            exportDataModel.setMaterialCatalogAccuracy("√");
            exportDataModel.setMaterialCatalogMatching("√");
            exportDataModel.setMaterialCatalogRepeatability("√");
            data.add(exportDataModel);
            exportExcel(
                    "大同市档案馆馆藏档案数据质量检测记录表",
                    data,
                    "ZD1",
                    "德拜",
                    addFile(""),
                    "2251-2500");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void exportExcel(String filePath,
                                   List<ExportDataModel> dataList,String unit,
                                   String submitter,
                                   String detectBatch,
                                   String fileNumber) throws Exception{
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("sheet1");


        // 设置样式
        CellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setFontHeightInPoints((short) 14);  // 设置字号为14
        font.setBold(true);  // 设置字体加粗
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);  // 设置水平居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);  // 设置垂直居中

        //表头
        List<String[]> headList = getheadList(unit,submitter,detectBatch,fileNumber);

        //获取样式
        CellStyle cellStyle = getCellStyle(workbook);
        style.setAlignment(HorizontalAlignment.CENTER);  // 设置水平居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);  // 设置垂直居中

        // 合并单元格并设置表头
        int rowIndex = 0;
        int colIndex = 0;
        for (String[] rowData : headList) {
            Row row = sheet.createRow(rowIndex++);
            colIndex = 0;
            for (String cellData : rowData) {
                Cell cell = row.createCell(colIndex++);
                cell.setCellValue(cellData);
                cell.setCellStyle(cellStyle);
                if (rowIndex == 1) {
                    Font font1 = workbook.createFont();
                    font1.setFontHeightInPoints((short) 16);  // 设置字号为24
                    font1.setBold(true);  // 设置字体加粗
                    style.setFont(font1);
                    cell.setCellStyle(style);
                }
            }
        }

        //合并单元格
        // 合并单元格，参数依次为起始行，结束行 ,起始列，结束列（索引0开始）
        sheet.addMergedRegion(new CellRangeAddress(0,2,0,11));//合并第一行到第三行的第0列到第11列
        sheet.addMergedRegion(new CellRangeAddress(3,3,0,1)); //合并第4行的第0列到第1列
        sheet.addMergedRegion(new CellRangeAddress(3,3,2,3)); //合并第4行的第2列到第3列
        sheet.addMergedRegion(new CellRangeAddress(3,3,4,6)); //合并第4行的第4列到第6列
        sheet.addMergedRegion(new CellRangeAddress(3,3,7,11)); //合并第4行的第7列到第11列

        sheet.addMergedRegion(new CellRangeAddress(4, 6,0,0));//合并第5行到第五行的第0列
        sheet.addMergedRegion(new CellRangeAddress(4, 4, 1, 11));//合并第5行,第1列到第12列
        sheet.addMergedRegion(new CellRangeAddress(5, 5, 1, 2));//合并第6行,第1列和第2列
        sheet.addMergedRegion(new CellRangeAddress(5, 5, 3, 6));//合并第6行,第3列到第6列
        sheet.addMergedRegion(new CellRangeAddress(5, 5, 7, 11));//合并第6行,第1列到第11列

        // 渲染数据
        if (dataList!= null) {

            dataList = sortList(dataList);
            int dataRowIndex = rowIndex;
            for (ExportDataModel exportDataModel : dataList) {
                Row row = sheet.createRow(dataRowIndex++);
                row.setRowStyle(style);
                row.createCell(0).setCellValue(exportDataModel.getArchiveId());       // 档号
                row.createCell(1).setCellValue(exportDataModel.getFileIntegrity());   // 检查内容
                row.createCell(2).setCellValue(exportDataModel.getFileAccuracy());              // 案卷
                row.createCell(3).setCellValue(exportDataModel.getPictureCount());          // 图片数量
                row.createCell(4).setCellValue(exportDataModel.getPictureClarity());        // 清晰度
                row.createCell(5).setCellValue(exportDataModel.getPictureMatching());            // 匹配性
                row.createCell(6).setCellValue(exportDataModel.getPictureRepeatability());       // 重复性
                row.createCell(7).setCellValue(exportDataModel.getMaterialCatalogCount());            // 数量
                row.createCell(8).setCellValue(exportDataModel.getMaterialCatalogIntegrity());          // 完整性
                row.createCell(9).setCellValue(exportDataModel.getMaterialCatalogAccuracy());           // 准确性
                row.createCell(10).setCellValue(exportDataModel.getMaterialCatalogMatching());          // 匹配性2
                row.createCell(11).setCellValue(exportDataModel.getMaterialCatalogRepeatability());     // 重复性2

            }
        }

        // 自动调整列宽
        for (int i = 0; i < colIndex; i++) {
            sheet.autoSizeColumn(i);
        }

        // 写入文件
        try (FileOutputStream outputStream = new FileOutputStream(filePath)) {
            workbook.write(outputStream);
        }

    }

    private static List<String[]> getheadList(String unit,
                                              String submitter,
                                              String detectBatch,
                                              String fileNumber) {
        // 定义表头数据
        List<String[]> headerData = new ArrayList<>();
        headerData.add(new String[]{"永和县档案馆文书档案数据质量检测记录表","","","","","","","","","","",""});
        headerData.add(new String[]{"","","","","","","","","","","",""});
        headerData.add(new String[]{"","","","","","","","","","","",""});
        headerData.add(new String[]{"全宗单位: "+unit, "", "数据提交方: "+submitter, "","检测批次: "+detectBatch,"","","起止档号: "+fileNumber,"","","",""});
        headerData.add(new String[]{"档号", "检查内容", "", "", "", "", "", "", "", "", "", ""});
        headerData.add(new String[]{"", "案卷", "", "图片", "", "", "", "材料目录", "", "", "", ""});
        headerData.add(new String[]{"", "完整性", "准确性", "图片数量", "清晰度", "匹配性", "重复性", "数量(条)", "完整性", "准确性", "匹配性", "重复性"});
        //headerData.add(new String[]{"", "完整性", "准确性", "图片数量", "清晰度", "匹配性", "重复性", "完整性", "准确性", "匹配性", "重复性"});
        return headerData;
    }

    private static CellStyle getCellStyle(Workbook workbook) {
        // 创建表头样式
        CellStyle headerStyle = workbook.createCellStyle();
        Font headerFont = workbook.createFont();
        headerFont.setBold(true);
        headerStyle.setFont(headerFont);
        return headerStyle;
    }



    public static String addFile(String fileName) throws Exception{
        String filePath = fileName+"/"+"此文件系统生成不允许删除"+".txt";
        File backupFile = new File(filePath);
        if (!backupFile.exists()) {
            backupFile.createNewFile();
        }

        LocalDate localDate = LocalDate.now();
        int year = localDate.getYear();
        int monthValue = localDate.getMonthValue();
        int day = localDate.getDayOfMonth();
        String currentDate = String.format("%02d%02d%02d",year,monthValue,day);
        // 读取文件内容
        List<String> list = Files.readAllLines(Paths.get(filePath));
        if(!list.isEmpty()){
            String content = list.getLast();
            // 查找以当前日期开头的数据，如 2024120401
            if (content.startsWith(currentDate)) {
                // 截取最后两个字符并加1
                String numberPart = content.substring(content.length() - 2);
                try {
                    int number = Integer.parseInt(numberPart);
                    number++;  // 增加1
                    String newData = content.substring(0, content.length() - 2) + String.format("%02d", number);

                    // 添加新的数据行（换行并插入新数据）
                    list.add(newData);
                    writeToFile(filePath,list);
                    return newData;
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        }

        String newData = currentDate + "01";
        list.add(newData);
        writeToFile(filePath,list);
        return newData;
    }

    // 向文件写入内容的方法
    private static void writeToFile(String filePath, List<String> content) throws IOException {
        Files.write(Paths.get(filePath), content, StandardOpenOption.TRUNCATE_EXISTING);
    }

    public static List<ExportDataModel> sortList(List<ExportDataModel> list){

        Comparator<ExportDataModel> comparatorByAgeDesc = (map1, map2) -> {
            String value1 = map1.getArchiveId();
            String value2 = map2.getArchiveId();
            return - value2.compareTo(value1);
        };
        Collections.sort(list, comparatorByAgeDesc);
        return list;
    }
}
